package com.shkco.xbjcc.security;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.shkco.xbjcc.domain.Login;
import com.shkco.xbjcc.domain.Permission;
import com.shkco.xbjcc.service.ILoginService;
import com.shkco.xbjcc.service.IPermissionService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.stream.Collectors;

@Component
public class LoginUserDetailsService implements UserDetailsService {

    @Autowired
    private ILoginService loginService;

    @Autowired
    private IPermissionService permissionService;

    /*
     * @Description: 设置用户信息方法
     * @Author: Director
     * @Date: 2022/10/10 17:33
     * @param username: 登录时填写的账号信息
     * @return: org.springframework.security.core.userdetails.UserDetails
     **/
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        // 1.获取用户信息
        Wrapper<Login> wrapper = new EntityWrapper<>();
        wrapper.eq("username", username);
        Login login = loginService.selectOne(wrapper);
        // 2.如果用户不为空，那么获取权限信息
        if (login != null){
            // 2.1.查询用户权限
            List<Permission> permissions = permissionService.selectByLoginId(login.getId());
            // 2.2.将用户权限单独获取出来封装到SimpleGrantedAuthority对象中，再放入到集合中
            List<SimpleGrantedAuthority> authorities = permissions.stream().map(p ->new SimpleGrantedAuthority(p.getSn())
            ).collect(Collectors.toList());
            // 2.3.方法返回值需要一个UserDetails，此处返回的User是他的子类
            return new User(
                    login.getUsername(),
                    login.getPassword(),
                    login.getEnabled(),
                    login.getAccountNonExpired(),
                    login.getCredentialsNonExpired(),
                    login.getAccountNonLocked(),
                    authorities);
        }
        // 3.如果用户信息为空，那么返回null即可
        return null;
    }
}